package com.nmgsr.ptmsapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.nmgsr.beans.requestdao.LoginReq;
import com.nmgsr.beans.responsedao.LoginRes;
import com.nmgsr.nettools.net.config.NetManager;
import com.nmgsr.nettools.net.retrofit.BaseResponse;
import com.nmgsr.ptmsapp.R;
import com.nmgsr.ptmsapp.config.PreferencesManager;
import com.nmgsr.ptmsapp.databinding.LoginActivityBinding;
import com.nmgsr.beans.service.Api;
import com.nmgsr.nettools.base.BaseActivity;
import com.nmgsr.nettools.net.retrofit.HttpHelper;
import com.nmgsr.nettools.net.retrofit.HttpResponseObserver;
import com.nmgsr.nettools.net.retrofit.HttpUtil;
import com.nmgsr.nettools.util.ToastUtil;
import com.nmgsr.ptmsapp.utils.SM2Util;


public class LoginActivity extends BaseActivity {
    private LoginActivityBinding mBinding;
    @Override
    protected int getLayoutId() {
        return R.layout.login_activity;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        mBinding = LoginActivityBinding.inflate(getLayoutInflater());
        View view = mBinding.getRoot();
        setContentView(view);
        String str[] = PreferencesManager.getUsername(LoginActivity.this);
        mBinding.username.setText(str[0]);
        mBinding.password.setText(str[1]);
        if (PreferencesManager.getUsername(LoginActivity.this)[2].equals("1")) {
            mBinding.cbRemember.setChecked(true);
        } else {
            mBinding.cbRemember.setChecked(false);
        }
        mBinding.getToken.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });

    }
    public void login() {
        String username = mBinding.username.getText().toString();
        String password = mBinding.password.getText().toString();
        if (!TextUtils.isEmpty(username)&&!TextUtils.isEmpty(password)){
            getToken(username, password);
        }else if (TextUtils.isEmpty(username)){
            ToastUtil.showToast("请输入用户名");
        }else if (TextUtils.isEmpty(password)){
            ToastUtil.showToast("请输入密码");
        }
    }

    private void getToken(String username, String password) {
        String encryptedHex = "";
        try {
            SM2Util.validateKeys();
            // 加密为C1C3C2格式HEX
            encryptedHex= SM2Util.encryptToC1C3C2Hex(password);
            Log.e("login", "C1C3C2 HEX密文: " + encryptedHex);
        } catch (Exception e) {
            Log.e("SM2Error", "加密失败", e);
            ToastUtil.showToast("安全模块错误：" + e.getMessage());
        }
        int tenantId = 0;
        int codeId = 0;
        String code = "string";
        LoginReq req = new LoginReq();
        req.setAccount(username);
        req.setPassword(encryptedHex);
        req.setTenantId(tenantId);
        req.setCodeId(codeId);
        req.setCode(code);
        showLoading("正在登录");
        HttpHelper.getInstance()
                .getService(Api.class)
                .userLogin(req)
                .compose(HttpUtil.defaultSchedulers())
                .compose(bindToLifecycle())
                .subscribe(new HttpResponseObserver<BaseResponse<LoginRes>>() {
                    @Override
                    protected void onSuccess(BaseResponse<LoginRes> response) {
                        dismissLoading();
                        if (response.getCode() == 200){
                            ToastUtil.showToast("登录成功");
                            String accessToken = response.getResult().getAccessToken();
                            Log.e("login", "onSuccess: " + accessToken);
                            String refreshToken = response.getResult().getRefreshToken();
                            NetManager.getInstance().appendHeader("Authorization", "Bear "+accessToken);
                            NetManager.getInstance().updateHeader();
                            String savePassword = "";
                            boolean isRemember = false;
                            if (mBinding.cbRemember.isChecked()) {
                                savePassword = password;
                                isRemember = true;
                            }
                            PreferencesManager.saveUsername(LoginActivity.this, username, savePassword, isRemember);
                            // 保存token到本地
                            PreferencesManager.saveToken(getApplicationContext(), accessToken);
                            // 登录成功，启动MainActivity
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            // 关闭当前登录活动
                            finish();

                        }else if (response.getCode() == 401){
                            ToastUtil.showToast("登录失败");
                        }else {
                            ToastUtil.showToast(response.getMessage());
                        }
                    }

                    @Override
                    protected void handleError(Throwable e) {
                        dismissLoading();
                        Log.e("e", "error: " + e.toString());
                        ToastUtil.showToast("登录失败");
                    }
                });
    }
}
